package com.example.firealarm.controller;

import com.example.firealarm.model.FireAlarmEvent;
import com.example.firealarm.service.FireAlarmNotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 消防报警控制器
 * 提供查询报警事件和设备状态的REST API
 */
@RestController
@RequestMapping("/api/fire-alarm")
public class FireAlarmController {

    @Autowired
    private FireAlarmNotificationService notificationService;

    /**
     * 获取当前活跃的报警事件
     *
     * @return 报警事件列表
     */
    @GetMapping("/active-alarms")
    public ResponseEntity<List<FireAlarmEvent>> getActiveAlarms() {
        List<FireAlarmEvent> alarms = notificationService.getActiveAlarms();
        return ResponseEntity.ok(alarms);
    }

    /**
     * 获取系统状态信息
     *
     * @return 系统状态
     */
    @GetMapping("/system-status")
    public ResponseEntity<Object> getSystemStatus() {
        // 构建系统状态信息
        return ResponseEntity.ok(buildSystemStatus());
    }

    /**
     * 构建系统状态信息
     */
    private Object buildSystemStatus() {
        List<FireAlarmEvent> activeAlarms = notificationService.getActiveAlarms();
        
        // 统计不同类型的报警数量
        long fireAlarmCount = activeAlarms.stream()
                .filter(e -> e.getEventType() == 0x01) // 火警
                .count();
        
        long faultCount = activeAlarms.stream()
                .filter(e -> e.getEventType() == 0x02) // 故障
                .count();
        
        long otherCount = activeAlarms.stream()
                .filter(e -> e.getEventType() != 0x01 && e.getEventType() != 0x02)
                .count();

        return new Object() {
            public final long totalAlarms = activeAlarms.size();
            public final long fireAlarms = fireAlarmCount;
            public final long faults = faultCount;
            public final long others = otherCount;
            public final String status = fireAlarmCount > 0 ? "火警" : 
                                        (faultCount > 0 ? "故障" : "正常");
        };
    }
}